package filter;

import com.alibaba.fastjson.JSON;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //所有的请求都先到达这里，经过检查后决定是否发给后面对应的servlet
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String[] urls = {"/api/books","/api/activeUser","/api/register","api/hotBooks","/api/hotBooks","/api/notice","/api/login"};//放行清单
        String path = request.getRequestURL().toString();
        boolean fangxing = false;
        for (String url : urls) {
            if (path.indexOf(url) > 0) {
                fangxing = true;
                break;
            }
        }
        if (fangxing == false) {
            HttpSession session = request.getSession();//这行代码会自动根据请求消息中头部set-cookie键带的值来获取对应session，如果没有就新建
            //怎么分析这个session对象是本次新创建的，还是上一次创建的:登录时创建的session添加一个属性user到里面。
            Response build = null;
            if (session.getAttribute("user") == null) {//如果session新创建的（肯定没有user），则表示这个用户还没有登录，是刚开始访问的，返回一段没有登录的json数据
                build = Response.build(ResponseCode.NOT_LOGIN);//返回未登录消息
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSON.toJSON(build).toString());
            } else {
                filterChain.doFilter(request, response);//已经登录，放行，该请求继续访问后面的servlet
                Cookie cookie = new Cookie("JSESSIONID", session.getId());
                cookie.setMaxAge(60*60);
                response.addCookie(cookie);
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
